package com.ramnight.sql2.core;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ramnight.sql2.component.Page;
import com.ramnight.sql2.component.RecList;
import com.ramnight.sql2.component.Record;

/**
 * 1.不提供批处理，利用事务来进行批处理。
 */
public class DB {
	private static DbDriver driver;
	
	public static boolean execute(String sql, Object... params){
		return driver.execute(sql, params) > 0;
	}
	
	/**
	 * 单个，单列
	 */
	public static <T> T findCol(String sql, Object...params) {
		return driver.find(sql, params);
	}
	
	public static Record find(String sql, Object...params){
		Map<String, Object> map = driver.findMap(sql, params);
		if(map == null){
			return null;
		}
		return new Record(map);
	}
	
	public static RecList search(String sql, Object...params){
		List<Map<String, Object>> mapList = driver.searchMapList(sql, params);
		if(mapList == null){
			return null;
		}
		RecList rList = new RecList();
		for(Map<String, Object> map : mapList){
			rList.add(new Record(map));
		}
		return rList;
	}
	
	public static List<Record> searchList(String sql, Object...params){
		List<Map<String, Object>> mapList = driver.searchMapList(sql, params);
		List<Record> list = new ArrayList<>();
		for(Map<String, Object> map : mapList){
			list.add(new Record(map));
		}
		return list;
	}
	
	/**
	 * 多个，单列
	 */
	public static <T> List<T> searchCol(String sql, Object...params){
		return driver.searchList(sql, params);
	}
	
	public static int count(String sql, Object...params){
		return Integer.parseInt(String.valueOf(findCol(sql, params)));//会返回Long型
	}
	
	/**
	 * 只支持包含一个from的sql（按from进行split）
	 */
	public static Page paginate(String sql, int pageNumber, int pageSize, Object...params){
		int fromIndex = sql.toLowerCase().indexOf("from");
		String sqlExceptSelect = sql.substring(fromIndex);
		
		int totalRow = count("select count(1) " + sqlExceptSelect, params);
		if(totalRow == 0){
			return new Page(new RecList(), pageNumber, pageSize, 0, 0);
		}
		
		int totalPage = totalRow / pageSize;
		if (totalRow % pageSize != 0) {
			totalPage++;
		}
		sql += " limit " + pageSize * (pageNumber - 1) + "," + pageSize;
		return new Page(search(sql, params), pageNumber, pageSize, totalPage, totalRow);
	}
	
	public static Connection startTransaction() {
		return driver.startTransaction();
	}
	
	public static void closeTransaction() {
		driver.closeTransaction();
	}

	static void setDriver(DbDriver driver){
		DB.driver = driver;
	}
}
